package ocbn.remotelab.events;

import ocbn.remotelab.xml.*;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.Connector;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.io.DataInputStream;
import java.io.EOFException;



/**
 * This class reads the XML log files puts the Event in a Vector. It then
 * appends the XML into a .txt file which is the XML log file.
 * @author Basem
 */
public class FileStorage {

    //Default path to log file
    public static final String DEF_LOG_FILE = "file:///SDCard/BlackBerry/MS.txt";

    /**
     * The name of the file to store the XML inside, which is a .txt log file.
     */
    private String fileName;
    /**
     * The XML to be appended to the file.
     */
    private String xmlCode;
    /**
     * The vector of events from an XML file.
     */
    private Vector eventsList;

    /**
     * Constructor for storing a file.
     * @param The fileName of the log file in the BB's local flash drive.
     */

    public FileStorage(String fileName, String xmlCode) {

        this.fileName = fileName;
        this.xmlCode = xmlCode;

    }

    /**
     * Coverts the XML information into a list(Vector) of events.
     * @param fileName The name of the txt file containing the XML code.
     */
    public void eventsList(String fileName) {

        XMLImport xml = new XMLImport();
        eventsList = xml.importXML(fileName);

    }

    /**
     * Appends the XML code  into a .txt log file.
     * @param fileName The path where the file is located on the BB.
     * @param xmlCode The code that will be appended to the log file.
     */
    public static void appendXML(String fileName, String xmlCode) {

        FileConnection file = null;

        try {
            //First, open a connection to the server.
            file = (FileConnection) Connector.open(fileName);


            /*Creates the file if it doesn't exist or it exists but is not
             *accessable.
             * */
            if (!file.exists()) {

                file.create();

            }
                OutputStream out = null;
                DataOutputStream outputXML = null;
                
                //Writing XML into the file.
                if (file.canWrite()) {

                    out = file.openOutputStream(file.fileSize());
                    out.flush();

                    outputXML = new DataOutputStream(out);
                    outputXML.writeUTF(xmlCode);

                    //When finished.
                    outputXML.flush();
                    outputXML.close();

                    //close connection.
                    file.close();
                }
          
        } catch (IOException ex) {
            ex.printStackTrace();      
        }       
    }

    /**
     * Return a Vector of all MSevents from default log file
     * @return a Vector of MSevents
     */
    public static Vector loadMSEvents(){
        return loadMSEvents(DEF_LOG_FILE);
    }

    /**
     * This method will be called to read MS events from a given path to log file,
     * @return a Vector of MSevents
     */
     public static Vector loadMSEvents(String filename){

         String s;
         FileConnection file;
         DataInputStream in;

         //create an empty vector to store the events from the file
         Vector MSEvents = new Vector();

         try {
             //Open up a connection to the file.
             file = (FileConnection)Connector.open(filename);
             in = file.openDataInputStream();
            
             XMLImport xml = new XMLImport();
             //read a testbyte to see if the file is empty.
             in.mark(1);
             int testRead = in.read(new byte[1]);
             in.reset();

             //file is not empty.
             if(testRead != -1){
                 //read the first line
                 s = in.readUTF();
                 while (in.available() > 0) {
                   //Create an event and add this event to the vector of events.
                     MSEvents.addElement(xml.importXML(s).elementAt(0));

                     //Read the next String
                     s = in.readUTF();

                 }
                 if (s != null) {
                     MSEvents.addElement(xml.importXML(s).elementAt(0));
                 }


              }
                 in.close();
                 file.close();

         } catch(IOException e){
             System.out.println("somethign happened with file");
                e.printStackTrace();
         }

         //return a vector of Events.
         return MSEvents;
     }

     /**
      * Clear the default log file, by deleting the file and recreating an empty
      * one with the same name.
      */
     public static void clearMSEvent(){
         clearMSEvent(DEF_LOG_FILE);
     }

     /**
      * Clears the content of a file by deleting the file and recreating
      * a new file of the same name.
      */
     public static void clearMSEvent(String filename){
         FileConnection file = null;
         try{
            file = (FileConnection)Connector.open(filename);

            if(file.exists()){
            file.delete();
            file.create();
            }
            file.close();
         } catch (IOException ex) {
            System.out.println("somethign happened");
           System.out.println(ex.getMessage());
        }
      }
     
}
